<template>
  <div id="editor"></div>
</template>
<script lang="ts" setup>
  import { onMounted, nextTick } from 'vue';
  import { useUserStore } from '/@/store/modules/user';

  const userStore = useUserStore();
  const serverInfo = userStore.getServerInfo;

  //实例化编辑器
  //建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
  function createEditor() {
    UE.getEditor('editor');
  }

  // 初始化上传路径 getActionUrl
  function initUeditorActionUrl(flowId, id, formCode) {
    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    const rootPath = serverInfo.rootPath;
    UE.Editor.prototype.getActionUrl = function (action) {
      if (action == 'uploadimage' || action == 'uploadscrawl') {
        return rootPath + '/ueditor/UploadFile';
      } else if (action == 'uploadvideo') {
        return rootPath + '/ueditor/UploadFile';
      } else {
        return this._bkGetActionUrl.call(this, action);
      }
    };
  }

  onMounted(() => {
    nextTick(() => {
      createEditor();
      // console.log('isUeditorActionUrlInited', isUeditorActionUrlInited);
      // 此处不能初始化两次，否则会导致 _bkGetActionUrl 的地址在第二次初始化时，成为了其本身，当调用getActionUrl时陷入循环，致堆栈溢出
      window.setTimeout(() => {
        initUeditorActionUrl('', '', '');
      }, 200);
    });
  });

  /**
   * @description: 写入内容
   * @param {*} isAppendTo 追加内容
   * @param {*} content 内容
   * @return {*}
   */
  function setContent(content, isAppendTo) {
    UE.getEditor('editor').setContent(content, isAppendTo);
  }

  //获得整个html的内容
  function getAllHtml() {
    return UE.getEditor('editor').getAllHtml();
  }
  //获得内容
  function getContent() {
    return UE.getEditor('editor').getContent();
  }
  //判断是否有内容
  function hasContent() {
    return UE.getEditor('editor').hasContents();
  }

  //使编辑器获得焦点
  function setFocus() {
    UE.getEditor('editor').focus();
  }

  //编辑器是否获得焦点
  function isFocus(e) {
    alert(UE.getEditor('editor').isFocus());
    UE.dom.domUtils.preventDefault(e);
  }
  //编辑器失去焦点
  function setblur(e) {
    UE.getEditor('editor').blur();
    UE.dom.domUtils.preventDefault(e);
  }
  //插入给定的内容
  function insertHtml(value) {
    // var value = prompt('插入html代码', '');
    UE.getEditor('editor').execCommand('insertHtml', value);
  }

  function exec(method) {
    UE.getEditor('editor').execCommand(method);
  }

  defineExpose({
    setContent,
    getAllHtml,
    getContent,
    hasContent,
    setFocus,
    isFocus,
    setblur,
    insertHtml,
    exec,
  });
</script>
